<?php

namespace App\Http\Controllers\DriverApp;


class Utils
{
    /**
     * 加密token
     * @param string $tokens
     * @return string
     */
    public static function EncryptToken(string $token) {
        return base64_encode($token);
    }

    /**
     * 解密token
     * @param string $token
     * @return false|string
     */
    public static function DecryptToken(string $token) {
        return base64_decode($token,true);
    }

    /**
     * 创建token
     * @param int $user_id
     * @return string
     */
    public static function CreateTokenByUserId($user_id) {
        $token = [
            'uid'=>$user_id,
            'until'=>time()+7*86400,
            'rand'=>Utils::Rand(9,''),
        ];
        return static::EncryptToken(json_encode($token,JSON_UNESCAPED_UNICODE));
    }

    /**
     * 根据token获取会员id
     * @param string $token
     * @return mixed
     */
    public static function GetUserIdByToken(string $token) {
        $tokens = json_decode(static::DecryptToken($token));
        return $tokens->uid;
    }

    /**
     * 随机字符串
     * @param int $length
     * @param string $chars
     * @return string
     */
    public static function Rand(int $length,string $chars) {
        if(!is_int($length) || $length < 1){
            $length = 6;
        }
        $str = '';
        if (strlen($chars) < 2){
            $chars = '1234567890';
        }
        for($i=0;$i<$length;$i++){
            $str .= $chars[mt_rand(0,strlen($chars)-1)];
        }
        return $str;
    }

    /**
     * @param string $data
     * @param string $key
     * @return string
     */
    public static function Encrypt(string $data, string $key) {
        if ($key == '') {
            $key = '12345678';
        }
        return base64_encode(openssl_encrypt($data,'RC2-CFB',$key,OPENSSL_RAW_DATA,$key));
    }

    /**
     * @param string $data
     * @param string $key
     * @return false|string
     */
    public static function Decrypt(string $data, string $key) {
        if ($key == '') {
            $key = '12345678';
        }
        return openssl_decrypt(base64_decode($data),'RC2-CFB',$key,OPENSSL_RAW_DATA,$key);
    }

    /**
     * 唯一订单号
     * @return string
     */
    public static function OrderNums() {
        $time = time();
        $order = date('Y',$time).date('m',$time).date('d',$time).date('H',$time).date('i',$time).date('s',$time).static::Rand(6,'1234567890');
        return $order;
    }
}
